package com.sinosoft.service.impl;

import com.sinosoft.domain.ApiException;
import com.sinosoft.domain.CodeEnums;
import com.sinosoft.domain.news.NewsListConditions;
import com.sinosoft.pojo.NewsList;
import com.sinosoft.repository.NewsListRepository;
import com.sinosoft.service.NewsListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hyy85
 * @version 1.0
 * @date: 19/6/2018 上午 10:12<br/>
 * @description 获取新闻列表业务实现
 * @since 1.8
 */
@Service
public class NewsListServiceImpl implements NewsListService {

    private final NewsListRepository newsListRepository;

    private static Logger logger = LoggerFactory.getLogger(NewsListServiceImpl.class);

    @Autowired
    public NewsListServiceImpl(NewsListRepository newsListRepository) {
        this.newsListRepository = newsListRepository;
    }

    @Override
    public List<NewsList> getAllNewsList(NewsListConditions conditions) {
        if (conditions == null) {
            throw new ApiException(CodeEnums.CONDITION_NULL);
        }
        int pageNo = conditions.getPageNo();
        int pageSize = conditions.getPageSize();
        if (pageNo < 0) {
            throw new ApiException(CodeEnums.PARA_ERR);
        }
        if (pageSize < 0) {
            pageSize = 20;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "addTime");
        PageRequest pageRequest = new PageRequest(pageNo,pageSize,sort);
        Page<NewsList> page;
        try {
            page = newsListRepository.findAll(pageRequest);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            throw new ApiException(CodeEnums.DATA_RW_ERROR);
        }
        List<NewsList> newsList = page.getContent();
        if (newsList == null || newsList.size() < 0) {
            throw new ApiException(CodeEnums.NO_DATA);
        }
        return newsList;
    }
}
